import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator

# 读取CSV文件
df = pd.read_csv('某超市销售数据.csv')

# 尝试将'销售额'列从字符串转换为浮点数
df['销售额'] = pd.to_numeric(df['销售额'], errors='coerce')  # 将无法转换的值设置为NaN

# 删除任何包含NaN的行
df = df.dropna(subset=['销售额'])

# 按"类别"分组并计算销售总额
grouped = df.groupby('类别')['销售额'].sum().reset_index()

# 计算每个类别的百分比
grouped['百分比'] = (grouped['销售额'] / grouped['销售额'].sum()) * 100

# 绘制饼图
fig, ax = plt.subplots(figsize=(8, 6))
ax.pie(grouped['销售额'], labels=grouped['类别'], autopct=lambda p: '{:.1f}%'.format(p), startangle=90)
plt.rcParams["font.sans-serif"] = ["SimHei"]  # 设置中文显示字体
# 设置饼图中心标签
ax.axis('equal')  # 确保饼图是圆的
center_circle = plt.Circle((0, 0), 0.70, fc='white')
fig = plt.gcf()
fig.gca().add_artist(center_circle)

# 添加标题
ax.set_title('销售总额(按类别)')

# 显示图形
plt.show()